<template>
  <el-dialog ref="houseDialog" :title="userId?'编辑房产':'添加房产'" :visible="dialogFormVisible" center @close="closeFn">
    <el-form ref="formData" :model="formData" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="经纪" prop="agent">
        <el-select v-model="formData.agent" placeholder="请选择" style="width:150px">
          <el-option
            v-for="item in screenList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="formData.category" placeholder="请选择" style="width:150px">
          <el-option
            v-for="item in classifyList"
            :key="item.id"
            :value="item.id"
            :label="item.title"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-tag
          v-for="tag in formData.tags"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="saveTagInput"
          v-model="inputValue"
          class="input-new-tag"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+新标签</el-button>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-row type="flex">
          <el-cascader
            v-model="address"
            :options="options"
            :props="SetKesDept"
            @change="addressFn"
          />
          <el-input v-model="formData.address" />
        </el-row>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="formData.price" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input
          v-model="formData.desc"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 10}"
          placeholder="请输入内容"
        />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <vue-editor v-model="formData.content" />
      </el-form-item>
      <el-form-item label="介绍图片" prop="photos">
        <ImageUpload ref="photos" :type="'photos'" />
      </el-form-item>
      <el-form-item label="封面" prop="image">
        <ImageUpload ref="image" :type="'image'" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" @click="OKFn">确 定</el-button>
      <el-button size="small" @click="closeFn">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { VueEditor } from 'vue2-editor'
import { setProperties, getProperty, editProperty, getAddressData } from '@/api/houseProperty'

// 上传文件组件
export default {
  components: {
    VueEditor
  },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false
    },
    screenList: {
      type: Array,
      default: () => []
    },
    classifyList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      SetKesDept: {
        children: 'districts',
        value: 'name',
        label: 'name',
        expandTrigger: 'hover'
      },
      inputVisible: false,
      address: [],
      inputValue: '',
      userId: '',
      options: [],
      formData: {
        'title': '',
        'desc': '',
        'image': '',
        'agent': '',
        'content': '',
        'address': '',
        'price': '',
        'photos': {},
        'tags': [],
        'category': '',
        'created_by': '',
        'updated_by': ''
      },
      rules: {
        title: [
          {
            required: true, message: '该项不能为空', trigger: 'blur'
          }
        ],
        desc: [
          {
            required: true, message: '该项不能为空', trigger: 'blur'
          }
        ]
      }
    }
  },
  async created() {
    const res = await getAddressData()
    const demo = this.processing(res.data.districts[0].districts)
    this.options = demo
  },
  methods: {
    // 数据处理
    processing(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].districts.length) {
          this.processing(data[i].districts)
        } else {
          delete data[i].districts
        }
      }
      return data
    },
    // 标签
    handleClose(tag) {
      this.formData.tags.splice(this.formData.tags.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      // 安全判定
      if (this.formData.tags.indexOf(inputValue) !== -1) {
        this.$message.warning('标签名不能重复')
      }
      if (this.inputValue) {
        this.formData.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 地址
    addressFn(value) {
      console.log(value)
      this.formData.address = value.join(',')
      this.address = []
      console.log(this.formData.address)
    },
    // 确认按钮
    async OKFn() {
      // 校验
      await this.$refs.formData.validate()
      // 获取介绍图片地址数组
      const photosList = await this.$refs.photos.fileList.map(item => item.url)
      // 获取封面图片地址
      const image = await this.$refs.image.fileList[0]?.url || ''
      // 判断是否有id
      if (this.userId) {
        // 有id发起修改请求
        editProperty({
          ...this.formData,
          image: image,
          photos: photosList
        })
      } else {
        // 没id发起新增请求
        setProperties({
          ...this.formData,
          image: image,
          photos: photosList
        })
      }
      // 提示
      this.$message.success(this.userId ? '编辑成功' : '添加成功')
      // 关闭弹窗
      this.closeFn()
    },
    // 编辑回显
    async hoseEdit(id) {
      // 获取指定id数据
      this.userId = id
      const { data } = await getProperty(id)
      this.formData = { ...data, 'tags': data.tags.length ? data.tags : [] }
      this.formData.category = this.formData.category.id
      this.formData.agent = this.formData.agent?.id
      // console.log(this.formData)
      const newPhotoList = []
      this.formData.photos.forEach(item => {
        newPhotoList.push({ url: item })
      })
      this.$refs.photos.fileList = newPhotoList
      this.$refs.image.fileList = [{ url: this.formData.image }]
    },
    // 取消按钮
    closeFn() {
      this.$nextTick(() => {
        // 清空表单
        this.formData = {
          'title': '',
          'desc': '',
          'image': '',
          'agent': '',
          'content': '',
          'address': '',
          'price': '',
          'photos': {},
          'tags': [],
          'category': '',
          'created_by': '',
          'updated_by': ''
        }
        // 清空id
        this.userId = ''
        // 清空校验结果
        this.$refs.formData.resetFields()
        // 重置介绍图片
        this.$refs.photos.fileList = []
        // 重置封面
        this.$refs.image.fileList = []
      })
      this.$emit('update:dialogFormVisible', false)
      this.$emit('refreshHouse')
    }
  }
}
</script>

<style  lang="scss" scoped>
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
